package com.chalk.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.chalk.common.constant.CommonConstants;
import com.chalk.common.exception.ServiceException;
import com.chalk.common.util.IdGenerator;
import com.chalk.common.util.Result;
import com.chalk.common.util.ResultCode;
import com.chalk.config.base.BaseController;
import com.chalk.config.security.SecurityPasswordUtil;
import com.chalk.config.security.SpringContextUtil;
import com.chalk.config.security.UserDetailsUtil;
import com.chalk.model.Member;

import com.chalk.model.SysUser;
import com.chalk.service.MemberService;

import com.chalk.service.SysUserRoleRelatedService;
import com.chalk.service.SysUserService;
import com.chalk.vo.SysUserVo;
import com.chalk.vo.UserVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.provider.token.ConsumerTokenServices;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Date;
import java.util.List;

/**
 * 系统用户表(SysUser)表控制层
 * @author maxiaoqiang
 * @since 2019-03-22 17:38:25
 */
@Api(value = "系统用户表接口", tags = "系统用户表模块")
@RestController
@RequestMapping("/v1/sysUser")
public class SysUserController extends BaseController {

    @Autowired
    MemberService memberService;
    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysUserRoleRelatedService userRoleRelatedService;


    @Autowired
    private ConsumerTokenServices consumerTokenServices;

    /**
     * @Author 86130
     * @Description //todo 系统用户列表查询
     * @methodName selectAll
     * @param current: 当前页数
     * @param size: 每页显示条数
     * @param sysUser: 查询实体
     * @return Result 返回统一结果类
     * @Date  2021/9/27 18:57
     **/
    @ApiOperation(value = "条件查询系统用户列表", notes = "条件查询系统用户列表", response = Result.class)
    @GetMapping
    public Result selectAll(Integer current, Integer size, SysUser sysUser) {
        String shopName = sysUser.getShopName();
        String userName = sysUser.getUserName();
        Page<UserVo> userByPage = new Page<>();
        if (shopName != null && !shopName.equals("") && !shopName.equals("undefined")) {//如果门店名不为空就以门店为条件查询
            List<UserVo> userVos = this.sysUserService.selectListByShopName(this.getPageVo(current, size), sysUser);
            userByPage.setRecords(userVos);
        } else {
            userByPage = this.sysUserService.getUserByPage(this.getPageVo(current, size), sysUser);
        }

        return Result.success(userByPage);
    }

    /**
     * @Author 86130
     * @Description //todo 通过主键查询单条数据
     * @methodName selectOne
     * @param id: 用户ID
     * @return Result 返回结果类
     * @Date  2021/9/27 18:58
     **/
    @ApiOperation(value = "查询系统用户表", notes = "查询系统用户表", response = Result.class)
    @GetMapping("{id}")
    public Result selectOne(
            @ApiParam(name = "id", value = "主键", required = true, example = "1")
            @PathVariable String id) {
        return Result.success(this.sysUserService.selectById(id));
    }


    /**
     * @Author 86130
     * @Description //todo 添加系统用户信息
     * @methodName insert
     * @param sysUser: 用户对象
     * @param result:
     * @return Result 返回结果类
     * @Date  2021/9/27 18:59
     **/
    @ApiOperation(value = "保存sysUser", notes = "保存sysUser", response = Result.class)
    @PostMapping
    public Result insert(
            @ApiParam(name = "sysUser", value = "传入json格式", required = true)
            @RequestBody @Valid SysUserVo sysUser, BindingResult result) {

        //用户账号改为手机号
        sysUser.setUserName(sysUser.getMobilePhone());
        sysUser.setRoleId(sysUser.getRoleIds()[0]);
        beanValidator(result);
        /*用户名唯一校验*/
        beanValidate(sysUser);

        sysUser.setUserId(IdGenerator.getIdStr());
        DateTime date = DateUtil.date();
        sysUser.setCreateTime(date);
        sysUser.setUpdateTime(date);
        Boolean f = this.sysUserService.insertAndRole(sysUser);


        return Result.success(f);
    }

    /**
     * @Author 86130
     * @Description //todo 修改用户密码
     * @methodName updatePwd
     * @param sysUser: 用户对象
     * @param oldPassword: 流密码
     * @return Result 返回结果类
     * @Date  2021/9/27 19:00
     **/
    @ApiOperation(value = "修改密码", notes = "修改密码", response = Result.class)
    @PostMapping("/updatePwd")
    public Result updatePwd(
            @ApiParam(name = "sysUser", value = "传入json格式", required = true)
            @RequestBody SysUser sysUser, @RequestParam("oldPassword") String oldPassword) {

        if (StringUtils.isEmpty(sysUser.getUserId())) {
            return Result.fail(ResultCode.PARAM_IS_INVALID);
        }
        if (StringUtils.isNotEmpty(oldPassword)) {
            SysUser temp = this.sysUserService.selectById(sysUser.getUserId());
            if (null == temp) {
                return Result.fail(ResultCode.USER_NOT_FOUND);
            }
            String encrypt = SecurityPasswordUtil.md5Encrypt(oldPassword);
            if (!encrypt.equals(temp.getPassword())) {
                return Result.fail("原始密码错误！");
            }
        }
        SysUser user = new SysUser();
        user.setUserId(sysUser.getUserId());
        /*md5 加密*/
        user.setPassword(SecurityPasswordUtil.md5Encrypt(sysUser.getPassword()));
        user.setUpdateTime(DateUtil.date());
        return Result.success(this.sysUserService.updateById(user));
    }

    /**
     *
     *
     * @param sysUser 实体对象
     * @return Result 返回统一结果model
     */
    /**
     * @Author 86130
     * @Description //todo 修改系统用户表
     * @methodName update
     * @param sysUser: 用户对象
     * @param result:
     * @return Result 返回结果类
     * @Date  2021/9/27 19:01
     **/
    @ApiOperation(value = "修改系统用户表", notes = "修改系统用户表", response = Result.class)
    @PutMapping
    public Result update(
            @ApiParam(name = "sysUser", value = "传入json格式", required = true)
            @RequestBody @Valid SysUserVo sysUser, BindingResult result) {
        beanValidator(result);
        if (StringUtils.isEmpty(sysUser.getUserId())) {
            return Result.fail(ResultCode.PARAM_IS_INVALID);
        }
        /*用户名唯一校验*/
        beanValidate(sysUser);
        sysUser.setUpdateTime(DateUtil.date());
        return Result.success(this.sysUserService.updateAndRole(sysUser));
    }

    /**
     * 用户唯一参数校验
     *
     * @param sysUser
     */
    private void beanValidate(SysUserVo sysUser) {
        if (!sysUser.getPassword().equals(sysUser.getConfirmPwd())) {
            throw new ServiceException(ResultCode.PASSWORD_SAME);
        }

        int count = this.sysUserService.selectCount(new EntityWrapper<SysUser>()
                .eq("user_name", sysUser.getUserName())
                .eq("is_deleted", CommonConstants.IsDeleted.NOTDEL.getValue())
                .ne("user_id", sysUser.getUserId() == null ? "" : sysUser.getUserId()));
        if (count > 0) {
            throw new ServiceException(ResultCode.NAME_REPEAT);
        }
    }


    /**
     * @Author 86130
     * @Description //todo 逻辑删除系统用户表
     * @methodName delete
     * @param ids: 主键集合
     * @return Result 返回结果类
     * @Date  2021/9/27 19:03
     **/
    @ApiOperation(value = "批量删除系统用户表", notes = "批量删除系统用户表", response = Result.class)
    @DeleteMapping
    public Result delete(
            @ApiParam(name = "ids", value = "传数组", required = true)
            @RequestBody String[] ids) {
        return Result.success(this.sysUserService.deleteBatchByPrimaryKey(ids));
    }

    private Page<SysUser> getPage(Integer current, Integer size) {
        Page<SysUser> page = new Page<>();
        if (current != null) {
            page.setCurrent(current);
        }
        if (size != null) {
            page.setSize(size);
        }
        return page;
    }

    private Page<UserVo> getPageVo(Integer current, Integer size) {
        Page<UserVo> page = new Page<>();
        if (current != null) {
            page.setCurrent(current);
        }
        if (size != null) {
            page.setSize(size);
        }
        return page;
    }

    /**
     * @Author 86130
     * @Description //todo 获取系统用户信息
     * @methodName
     * @param
     * @return null
     * @Date  2021/9/27 19:04
     **/
    @ApiOperation(value = "获取系统用户信息", notes = "获取系统用户信息", response = Result.class)
    @GetMapping("/getSysUserInfo")
    public Result getSysUserInfo() {
        /* 获取操作用户 */
        SysUser sysUser = (SysUser) UserDetailsUtil.getUserInfo("sysUserService", "user_name");
        // 密码不返回
        if (null != sysUser) {
            sysUser.setPassword(null);
        }
        return Result.success(sysUser);
    }

    /**
     * 平台用户信息注销
     *
     * @param request
     * @return Result 返回统一结果model
     */
    @ApiOperation(value = "注销平台用户信息", notes = "注销平台用户信息", response = Result.class)
    @DeleteMapping("/logout")
    public Result revokeToken(HttpServletRequest request) {
        String token = SpringContextUtil.extractHeaderToken(request);
        consumerTokenServices.revokeToken(token);
        return Result.success();
    }

    /**
     * 销售人员查看所属门店
     * @param userId
     * @return
     */
    @GetMapping("/shopNames")
    public Result searchShopNameByUserId(String userId) {
        List<String> names = this.sysUserService.searchShopNameByUserId(userId);
        for (int i = 0; i < names.size(); i++) {
            System.out.println("names-----" + names.get(i));
        }
        return Result.success(names);
    }


}